package com.znxs.user_center_c.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.znxs.user_center_c.common.ErrorCode;
import com.znxs.user_center_c.exception.BusinessException;
import com.znxs.user_center_c.mapper.UserMapper;
import com.znxs.user_center_c.model.dto.UserUpdateRequest;
import com.znxs.user_center_c.model.entity.User;
import com.znxs.user_center_c.model.vo.UserVO;
import com.znxs.user_center_c.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.znxs.user_center_c.contant.userContent.USER_LOGIN_STATE;

/**
 * @author znxs
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2023-08-30 15:19:35
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;
    public static final String SALT = "znxs";

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 非空校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户不长度小于4位");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度小于8位");
        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户不能包含特殊字符");
        }
        // 密码和校验密码需要相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码和校验密码需要相同");
        }
        // 账户不能重复  [这里查询数据库，如果能放到后面就放到后面，减少资源调用]
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_account", userAccount);
        Long one = userMapper.selectCount(userQueryWrapper);
        if (one > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户不能重复");
        }
        // 星球编号不能重复
        userQueryWrapper = new QueryWrapper<>();
        Long count = userMapper.selectCount(userQueryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号不能重复");
        }
        // 密码加密
        final String SALT = "znxs";
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        boolean reusltSave = this.save(user);
        if (!reusltSave) return -1;
        return user.getId();
    }

    @Override
    public UserVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 非空校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            // todo 等会添加成自定义异常
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户不能重复");
        }
        // 密码加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 查询用户是否存在
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_account", userAccount);
        userQueryWrapper.eq("user_password", encryptPassword);
        User user = userMapper.selectOne(userQueryWrapper);
        if (user == null) {
            log.info("user login failed ,userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        // 脱敏
        UserVO safetyUser = getSafetyUser(user);
        // 记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, safetyUser);
        return safetyUser;
    }

    /**
     * 用户脱敏
     *
     * @param oldUser 没有脱敏的用户
     * @return 脱敏后的用户
     */
    @Override
    public UserVO getSafetyUser(User oldUser) {
        if (oldUser == null) return null;
        log.info(oldUser.toString());
        UserVO userVO = UserVO.objToVO(oldUser);
        log.info(userVO.toString());
        return userVO;
    }

    @Override
    public int outLogin(HttpServletRequest request) {
        // 移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }

    // todo 优化，后面这两个方法可以合并成一个
    @Override
    public int userClose(HttpServletRequest request) {
        // 获取当前登录用户
        UserVO loginUser = (UserVO) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NO_AUTH, "未登录");
        }
        // 查库
        User user = this.getById(loginUser.getId());
        // 非空判断
        if (user == null) {
            throw new BusinessException(ErrorCode.SYS_ERROR, "用户不存在");
        }
        // 注销用户操作，更改用户状态，改为不启用（todo 超过30天改为删除状态）
        UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
        userUpdateWrapper.eq("id", user.getId()).set("user_status", 0);
        int update = userMapper.update(user, userUpdateWrapper);
        if (update < 1) {
            throw new BusinessException(ErrorCode.SYS_ERROR, "修改状态失败");
        }
        return update;
    }

    @Override
    public int userRestore(HttpServletRequest request) {
        // 获取当前登录用户
        UserVO loginUser = (UserVO) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NO_AUTH, "未登录");
        }
        // 查库
        User user = this.getById(loginUser.getId());
        // 非空判断
        if (user == null) {
            throw new BusinessException(ErrorCode.SYS_ERROR, "用户不存在");
        }
        // 用户恢复注销操作，更改用户状态，改为启用
        UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
        userUpdateWrapper.eq("id", user.getId()).set("user_status", 1);
        int update = userMapper.update(user, userUpdateWrapper);
        if (update < 1) {
            throw new BusinessException(ErrorCode.SYS_ERROR, "修改状态失败");
        }
        return update;
    }

    @Override
    public int updateUserInfo(UserUpdateRequest userUpdateRequest, HttpServletRequest request) {
        // 非空判断
        if (userUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        // 判断是否登录
        UserVO loginUser = (UserVO) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NO_AUTH, "未登录");
        }
        // todo 参数进行校验，进行判断
        // 进行修改
        UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        userUpdateWrapper.eq("id", user.getId());
        boolean update = this.update(user, userUpdateWrapper);
        return update ? 1 : 0;
    }

    @Override
    public List<String> watchUserSignSystem(HttpServletRequest request) {
        return null;
    }


}




